'use strict';

var serviceUrl = '/gdp'
var commServices = {
    init:function(){
        this.setSearchColumn();
        this.isPage();
    },
    isPage:function(){
        var that = this;
        $.getJSON(serviceUrl + '/business/moreJoinTable/isPage',{ serviceId: serviceId })
            .done(function (res) {
                if (res.data.ispagination === 1){
                    that.createPageTable()
                }else {
                    that.createTable()
                }
            })
            .error(function () {
                bootbox.alert("获取数据失败!");
                return;
            });
    },
    createPageTable:function(){
        $("#tb_list").bootstrapTable('destroy')
            .bootstrapTable({
                url: serviceUrl + '/business/moreJoinTable/moreJoinTableServerByPage',
                undefinedText: '-',
                method: 'get',
                pagination: true,
                striped: true,
                cache: false,
                pageList: [5, 10, 20],
                toolbar: "#toolbar",
                showColumns: true,
                showRefresh: true,
                sidePagination: "server",
                responseHandler:function(res){
                    return {
                        "total": res.data.total,//总页数
                        "rows": res.data.rows   //数据
                    };
                },
                queryParams: this.getQueryParams,
                columns: this.getTableColumn()
            });
    },

    createTable:function(serviceId){
        $("#tb_list").bootstrapTable('destroy')
            .bootstrapTable({
                url: serviceUrl + '/business/moreJoinTable/moreJoinTableServer',
                undefinedText: '-',
                striped: true, // 是否显示行间隔色
                cache: false, // 是否使用缓存
                showColumns: true,
                showRefresh: true,
                queryParams: this.getQueryParams,
                responseHandler: function (res) {
                    return res.data.rows;
                },
                columns: this.getTableColumn()
        });
    },
    getQueryParams: function(pageReqeust){
        var params = {
            serviceId: serviceId,
            pageNO: pageReqeust.offset / pageReqeust.limit + 1,
            pageSize: pageReqeust.limit
        };

        var conQuery = { };

        $.each($('#txtSearch').children('.form-control'),function (index,item) {
            var idArr = $(item).attr('id').split('|');
            var value = $(item).val();
            var param = {};
            $.each(idArr,function(i, id){
                param[id] = value;
            });
            $.extend(conQuery, param)
        });
        $.extend(params,{ conQuery: JSON.stringify(conQuery) });
        return params
    },
    getTableColumn: function () {//设置表格显示列
        var columns = [];
        var columnRecord = [];
        var columnData = new Array();
        $.ajax({
            url: serviceUrl + '/business/moreJoinTable/selectAllColumn',
            type: 'get',
            async: false,
            data: { serviceId: serviceId },
            dataType: "json"
        }).done(function (res) {
            columnData = res.data;
        }).error(function () {
            bootbox.alert("显示列数据加载失败!");
            return;
        });
        $.each(columnData, function (i, e) {
            var fileName = e.filedname || e.fieldname;
            var filedNameCn = e.fieldcaption || e.fieldnamecn;
            var obj = { "field":fileName, "title": filedNameCn, "align": 'center', "valign": 'middle' };
            if (columnRecord.indexOf(fileName) === -1) {
                columns.push(obj);
                columnRecord.push(fileName);
            }
        });
        return columns;
    },
    setSearchColumn: function () {
        $.ajax({
            url: serviceUrl + '/business/moreJoinTable/selectQueryFiled',
            type: 'get',
            async: false,
            data: { serviceId: serviceId },
            dataType: "json"
        }).done(function (res) {
            $.each(res.data, function (i, e) {
                if (setQueryColumn(e)){
                    $("#txtSearch").append("<label style='margin-left:10px;' filedname='"+ e.fieldnamecn +"' for='" + e.fieldname + "'>" + e.fieldnamecn + "：</label>");

                    switch (e.showtype) {
                        case "0"://文本框
                            $("#txtSearch").append("<input id='" + e.fieldname + "' placeholder='请输入" + e.fieldnamecn + "' type='text' class='form-control' >");
                            break;
                        case "1"://下拉框
                            var strtxt = "<select id='" + e.fieldname + "'  class='form-control' >"
                                + "<option value=''>请选择</option>";
                            if (e.enumvalue != null && e.enumvalue != "") {
                                var enums = e.enumvalue.split(',');
                                for (var i = 0; i < enums.length; i++) {
                                    var eb = enums[i].split(':');
                                    strtxt += "<option value='"+eb[0]+"'>"+eb[1]+"</option>";
                                }
                            }
                            strtxt += "</select>";
                            $("#txtSearch").append(strtxt);
                            break;
                        case "4"://日期框
                            $("#txtSearch").append("<input id='" + e.fieldname + "' value='"+ today() +"' data-date-format='yyyy-mm-dd HH:mm:ss' type='text' class='form-control' >");
                            $("#" + e.fieldname + "").datetimepicker({
                                language: 'zh-CN',
                                autoclose:true,
                                autoUpdateInput: true
                            });
                            break;
                    }
                }
            });
        }).error(function () {
            bootbox.alert("显示列数据加载失败!");
            return;
        });
    }
}

var setQueryColumn = function(item) {
    var $lable = $('#txtSearch').find('label[filedname="'+ item.fieldnamecn +'"]');
    if ($lable.length > 0) {
        var id = $lable.attr('for') + '|' + item.fieldname;
        $lable.attr('for', id);
        $lable.next().attr('id',id)
        return false
    }
    return true;
}

var today = function(){
    var date = new Date();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
    var day = date.getDate()  < 10 ? '0' + date.getDate() : date.getDate();
    return date.getFullYear() + '-' + month + '-' + day + ' 08:00:00';
}

//服务初始化
$(function () {
    $("#sp_seviceUrl").append("服务地址：" + serviceUrl + "/business/moreJoinTable/moreJoinTableServer");
    $("#sp_seviceUrl").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务ID：" + serviceId);

    commServices.init();
    $('#querySingleTB span').text(serviceUrl + "/business/moreJoinTable/moreJoinTableServerByPage?serviceId=" + serviceId);

    $("#btn_search").click(function () {
        $("#tb_list").bootstrapTable('refresh');
    });
});
